﻿using Dyao.Book.Application.Abstractions;
using Foundation.Core;

namespace Dyao.Book.Application
{
    [TaskCenterRuleName(RuleKey, DisplayName = "测试任务规则")]
    public class TestTaskRuleExcutor : TaskRuleExcutorBase, ITaskRuleExcutor<TestTaskRuleExcutorModel>, ITaskRuleSettingsLoader, ITransientDependency
    {
        public const string RuleKey = TaskCenterRuleExcutorKeyInfo.TestTaskRuleKey;
        private TestTaskRuleExcutorModel _setting;
        private readonly ITaskCenterRecordApplication _taskCenterRecordService;

        public TestTaskRuleExcutor(ITaskCenterRecordApplication taskCenterRecordService)
        {
            this._taskCenterRecordService = taskCenterRecordService;
        }

        public override string Key => RuleKey;

        public TestTaskRuleExcutorModel Settings => _setting;

        public override async Task ExcuteAsync(TaskCenterRuleExcutingContext context)
        {
            if (_setting == null) return;

            if (_setting.OneUserHaveOneTask)
            {
                var isUserHaveRuningTask = await _taskCenterRecordService.IsCurrentUserHaveRunningTaskAsync();
                if (isUserHaveRuningTask)
                {
                    throw new BusinessException("testtaskruleexcutor.excuteasync", "已经存在其他还未完成的任务，请稍后再试");
                }
            }
            if (_setting.TaskOnlyHaveOneRuning)
            {
                var isTaskHaveOtherRunning = await _taskCenterRecordService.IsHaveCurrentTaskRunningAsync(context.TaskCode);
                if (isTaskHaveOtherRunning)
                {
                    throw new BusinessException("testtaskruleexcutor.excuteasync", "当前任务存在未完成的，请稍后再试");
                }
            }
        }

        public void LoadSettings(string settingsStr)
        {
            _setting = Deserialize<TestTaskRuleExcutorModel>(settingsStr);
        }
    }
}
